package com.lai.gulimall.auth.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.TypeReference;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lai.common.constant.AuthServerConstant;
import com.lai.common.exception.BizCodeEnum;
import com.lai.common.exception.RRException;
import com.lai.common.vo.MemberRespVo;
import com.lai.common.to.SocialUserDto;
import com.lai.common.utils.R;
import com.lai.gulimall.auth.config.Oauth2GitHubConfigProperties;
import com.lai.gulimall.auth.config.Oauth2GiteeConfigProperties;
import com.lai.gulimall.auth.config.Oauth2WeiBoConfigProperties;
import com.lai.gulimall.auth.feign.MemberFeignService;
import com.lai.gulimall.auth.service.Oauth2Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class Oauth2ServiceImpl implements Oauth2Service {

    @Autowired
    Oauth2WeiBoConfigProperties oauth2WeiBoConfigProperties;

    @Autowired
    Oauth2GiteeConfigProperties oauth2GiteeConfigProperties;

    @Autowired
    Oauth2GitHubConfigProperties oauth2GitHubConfigProperties;

    @Autowired
    MemberFeignService memberFeignService;

    @Override
    public MemberRespVo weibo(String code) {
        //构建请求参数
        Map<String, Object> accessTokenQueryMap = new HashMap<>();
        accessTokenQueryMap.put("client_id", oauth2WeiBoConfigProperties.getClient_id());
        accessTokenQueryMap.put("client_secret", oauth2WeiBoConfigProperties.getClient_secret());
        accessTokenQueryMap.put("grant_type", oauth2WeiBoConfigProperties.getGrant_type());
        accessTokenQueryMap.put("redirect_uri", oauth2WeiBoConfigProperties.getRedirect_uri());
        accessTokenQueryMap.put("code", code);
        //发送请求获取access_token
        String accessTokenJsonMap = HttpUtil.post("https://api.weibo.com/oauth2/access_token", accessTokenQueryMap);
        //把json转换成Map对象
        Gson gson = new Gson();
        Map<String, String> accessTokenMap = gson.fromJson(accessTokenJsonMap, new TypeToken<Map<String, String>>() {
        }.getType());
        //获取access_token 和 uid
        String access_token = accessTokenMap.get("access_token");
        String uid = accessTokenMap.get("uid");
        if (!StringUtils.isEmpty(access_token) && !StringUtils.isEmpty(uid)) {
            //根据获取access_token和 uid获取用户的详细信息
            Map<String, Object> userInfoQueryMap = new HashMap<>();
            userInfoQueryMap.put("access_token", access_token);
            userInfoQueryMap.put("uid", uid);
            /*String userInfoJsonMap = HttpUtil.get("https://api.weibo.com/2/users/show.json", userInfoQueryMap);*/
            String userInfoJsonMap = HttpRequest.get("https://api.weibo.com/2/users/show.json").form(userInfoQueryMap).execute().body();
            // TODO weibo接口 userInfoJsonMap转换出错 error
            Map<String, String> userJsonMap = gson.fromJson(userInfoJsonMap, new TypeToken<Map<String, Object>>() {
            }.getType());
            //封装数据
            String city = userJsonMap.get("location");
            String header = userJsonMap.get("profile_image_url");
            String username = userJsonMap.get("name");
            String nickname = userJsonMap.get("screen_name");
            String gender = userJsonMap.get("gender");
            String sign = userJsonMap.get("description");
            SocialUserDto socialUserDto = new SocialUserDto();
            socialUserDto.setSocialId(uid);
            socialUserDto.setUsername(username);
            socialUserDto.setNickname(nickname);
            socialUserDto.setCity(city);
            socialUserDto.setHeader(header);
            socialUserDto.setSign(sign);
            socialUserDto.setGender("m".equals(gender) ? 1 : 0);
            socialUserDto.setSocialType(AuthServerConstant.Oauth2Enum.Oauth2_PLATFORM_WEIBO.getCode());
            R r = memberFeignService.oauth2Login(socialUserDto);
            if(r.getCode() == 0){
                MemberRespVo data = r.getData(new TypeReference<MemberRespVo>() {
                });
                return data;
            }else{
                throw new RRException(BizCodeEnum.ACCOUNT_PASSWORD_INVALID_EXCEPTION.getMsg(),BizCodeEnum.ACCOUNT_PASSWORD_INVALID_EXCEPTION.getCode());
            }
        }
        return null;
    }

    //TODO GITHUB接口  网络超时
    @Override
    public MemberRespVo github(String code) {
        //构建请求参数
        Map<String, Object> map = new HashMap<>();
        map.put("client_id", oauth2GitHubConfigProperties.getClient_id());
        map.put("client_secret", oauth2GitHubConfigProperties.getClient_secret());
        map.put("redirect_uri", oauth2GitHubConfigProperties.getRedirect_uri());
        map.put("code", code);
        //发送请求获取access_token
        String response = HttpUtil.post("https://github.com/login/oauth/access_token", map);
        //根据&分割    access_token=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&scope=&token_type=bearer
        String[] split = response.split("&");//access_token=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
        String[] access_token = split[0].split("=");
        if (!StringUtils.isEmpty(access_token)) {
            String userInfoJsonMap = HttpRequest.get("https://api.github.com/user").header("Authorization", "token " + access_token).execute().body();
            Gson gson = new Gson();
            Map<String, String> userJsonMap = gson.fromJson(userInfoJsonMap, new TypeToken<Map<String, String>>() {
            }.getType());
            //封装数据
            String socialId = userJsonMap.get("id");
            String username = userJsonMap.get("login");
            String header = userJsonMap.get("avatar_url");
            String sign = userJsonMap.get("bio");
            String email = userJsonMap.get("email");
            String city = userJsonMap.get("location");
            String nickname = userJsonMap.get("name");
            SocialUserDto socialUserDto = new SocialUserDto();
            socialUserDto.setSocialId(socialId);
            socialUserDto.setUsername(username);
            socialUserDto.setHeader(header);
            socialUserDto.setSign(sign);
            socialUserDto.setEmail(email);
            socialUserDto.setCity(city);
            socialUserDto.setNickname(nickname);
            socialUserDto.setSocialType(AuthServerConstant.Oauth2Enum.Oauth2_PLATFORM_GITHUB.getCode());
            R r = memberFeignService.oauth2Login(socialUserDto);
            if(r.getCode() == 0){
                MemberRespVo data = r.getData(new TypeReference<MemberRespVo>() {
                });
                return data;
            }else{
                throw new RRException(BizCodeEnum.ACCOUNT_PASSWORD_INVALID_EXCEPTION.getMsg(),BizCodeEnum.ACCOUNT_PASSWORD_INVALID_EXCEPTION.getCode());
            }
        }
        return null;

    }

    @Override
    public MemberRespVo gitee(String code) {
        //构建请求参数
        Map<String, Object> map = new HashMap<>();
        map.put("client_id", oauth2GiteeConfigProperties.getClient_id());
        map.put("client_secret", oauth2GiteeConfigProperties.getClient_secret());
        map.put("grant_type", oauth2GiteeConfigProperties.getGrant_type());
        map.put("redirect_uri", oauth2GiteeConfigProperties.getRedirect_uri());
        map.put("code", code);
        //发送请求获取access_token
        String response = HttpUtil.post("https://gitee.com/oauth/token", map);
        //把json转换成Map对象
        Gson gson = new Gson();
        Map<String, String> jsonMap = gson.fromJson(response, new TypeToken<Map<String, String>>() {
        }.getType());
        String access_token = jsonMap.get("access_token");
        if (!StringUtils.isEmpty(access_token)) {
            Map<String, Object> userInfoQueryMap = new HashMap<>();
            userInfoQueryMap.put("access_token",access_token);
           /* String userInfoJsonMap = HttpUtil.get("https://gitee.com/api/v5/user", userInfoQueryMap);*/
            String userInfoJsonMap = HttpRequest.get("https://gitee.com/api/v5/user").form(userInfoQueryMap).execute().body();
            Map<String, String> userJsonMap = gson.fromJson(userInfoJsonMap, new TypeToken<Map<String, String>>() {
            }.getType());
            String socialId = userJsonMap.get("id");
            String username = userJsonMap.get("login");
            String header = userJsonMap.get("avatar_url");
            String sign = userJsonMap.get("bio");
            String email = userJsonMap.get("email");
            String nickname = userJsonMap.get("name");
            SocialUserDto socialUserDto = new SocialUserDto();
            socialUserDto.setSocialId(socialId);
            socialUserDto.setUsername(username);
            socialUserDto.setHeader(header);
            socialUserDto.setSign(sign);
            socialUserDto.setEmail(email);
            socialUserDto.setNickname(nickname);
            socialUserDto.setSocialType(AuthServerConstant.Oauth2Enum.Oauth2_PLATFORM_GITEE.getCode());
            R r = memberFeignService.oauth2Login(socialUserDto);
            if(r.getCode() == 0){
                MemberRespVo data = r.getData(new TypeReference<MemberRespVo>() {
                });
                return data;
            }else{
                throw new RRException(BizCodeEnum.ACCOUNT_PASSWORD_INVALID_EXCEPTION.getMsg(),BizCodeEnum.ACCOUNT_PASSWORD_INVALID_EXCEPTION.getCode());
            }
        }
        return null;
    }
}
